import platform
import flags
import os


if platform.machine().startswith('arm'):
    import simplejson as json
else:
    import json


class Trip():
    
    
    def __init__(self):

        self.status = 'unknown'

        #self.sensors = Sensors()
        self.sensors = LogReader('triplog20100806.json')
        
        self.TAB_place = Place()
        self.TAB_trans = Route()
        
        self.cur_place_time_cnt = 0
        self.cur_place_id = None

        self.cur_trans_time_cnt = 0
        self.cur_trans_id = None

        self.deli = None
        self.wait_10mins = None


    def detect(self):

        if self.status == 'unknown':
            if self.deli == None:
                self.deli = [True,False,False,True]
            re1 = self.isfirst_place()

        elif self.status == 'place':
            self.is_start_transition()

        elif self.status == 'transition':
            self.is_arrive_place()


    ############################################
    def isplace(self,readings):

        wifis = readings['wifi']
        re = set(wifis[0]) & set(wifis[-1])
        if len(re) >0:
            print "find a place"
            return True
        else:
            return False
        
        
    def get_placeid(self, readings):

        place_ids = self.TAB_place.lookup(self.sensors.readings)
        if len(place_ids) == 1:
            self.cur_place_id = place_ids[0]
            self.TAB_place.update(self.sensors.readings)
            self.status == 'place'

        elif len(place_ids) ==0:
            self.cur_place_id = self.TAB_place.new(self.sensors.readings)
            self.status == 'place'
    
        
    def isfirst_place(self):

        if self.wait_10mins != None and self.wait_10mins <600: # wait till 10mins
            self.sensors.read(self.deli)
            self.wait_10mins += 5
            return None

        if self.wait_10mins == None: # when just start the system
            self.sensors.read(self.deli)
            self.wait_10mins = 5
            self.deli = [True,False,False,False]
            
        elif self.wait_10mins >= 600: # after 10 mins
            self.deli = [True,False,False,True]
            self.sensors.read(self.deli)
            self.wait_10mins = None
            if self.isplace(self.sensors.readings):
                self.get_placeid(self.sensors.readings)
            self.sensors.reset()

    ################################################    
    def istrans(self, readings):
        """
        True:  in a transition
        False: not in a transition
        None:  dont know
        """
        pass

    def is_start_transition(self):
        cell,acc,gps,wifis = self.sensors.read(self.deli)
        re = self.istrans()
        if re == False:# still in place
            self.TAB_place.place_update(self.sensors.readings)
            self.sensors.reset()
        if re == None: # might start trans
            self.sensors.incr_deli()

        if re == True: # in trans
            self.status == 'transition'
            self.cur_trans_time_cnt = 5
            self.cur_trans_id = [self.cur_place_id]
        
    ################################################    
    def is_arrive_place(self):
        cell,acc,gps,wifis = self.sensors.read(self.deli)
        re = self.isplace()
        if re == False: #still in the transition
            self.TAB_trans.lookup(self.sensors.readings)
            self.cur_trans_time_cnt += 5
        if re == None: # close to a place
            self.deli = [True,True,True,True]
            self.TAB_trans.lookup(self.sensors.readings)
            self.cur_trans_time_cnt += 5
        if re == True: # arrive at a place
            self.status = 'place'
            self.TAB_trans.save(self.sensors.readings)



"""        
#################################################
import n900dev

class Sensors():
    
    
    def __init__(self):
        self.cell = n900dev.Celluar()
        self.acc = n900dev.Accel()
        self.gps = n900dev.GPS()
        self.wifi = n900dev.Wlan()
        self.readings = {'cell':[],'acc':[],'gps':[],'wifi':[]}
        self.accum = 0

    def read(self,deli)
        if deli[0] == True:
            self.cell.read()
            cellid = str(self.cell.cell['lac']) + str(self.cell.cell['cid'])
            self.readings['cell'].append(cellid)
        else:
            self.readings['cell'].append(None)

        if deli[1] == True:
            self.acc.read(50)
            re = self.ismove(self.acc.coords)
            self.readings['acc'].append(re)
        else:
            self.readings['acc'].append(None)

        if deli[2] == True:
            self.gps.read()
            self.readings['gps'].append(self.gps.coords)
        else:
            self.readings['gps'].append(None)

        if deli[3] == True:
            self.wifi.scan()
            self.wifi.aps.keys
            self.readings['wifi'].append(self.wifi.aps.keys)
        else:
            self.readings['wifi'].append(None)
            

    def ismove(self,accs):
        x1=None
        y1=None
        z1=None
        sumx = 0
        sumy = 0
        sumz = 0
        for coord in accs:
            x = coord[0]
            y = coord[1]
            z = coord[2]
            if x1!=None and y1!= None and z1!= None:
                sumx = sumx + abs(x1-x)
                sumy = sumy + abs(y1-y)
                sumz = sumz + abs(z1-z) 
            x1=x
            y1=y
            z1=z
        ave = (sumx/samples+sumy/samples+sumz/samples)/3
        if ave > 8 and self.accum > 0:
            self.accum -= 1
        if ave <= 8 and self.accum <6:
            self.accum += 1
        if ave > 8 and self.accum <= 4:
            return True
        elif ave <= 8 and self.accum >=6:
            return False

    def reset(self):
        self.readings = {'cell':[],'acc':[],'gps':[],'wifi':[]}
"""            


class Route():
    
    
    def __init__(self):
        pass



class Place():
    
    
    def __init__(self):
        self.TAB_place = {}
        self.load()

    def lookup(self, readings):
        return []

    def new(self,readings):

        newid = len(self.TAB_place)
        
        nw = []        
        for i in readings['wifi']:
            if i != None:
                nw.append(i)
        
        celllist = readings['cell']
        cids, cchs = self.cnt_cell(celllist)

        data = {'wifi':nw, 'cell':cids}
        self.TAB_place[newid] = data

        self.save()
        return newid


    def cnt_cell(self,celllist):

        cellids = {}
        cellchs = {}
        last_cell = None
        for cell in celllist:
            if last_cell ==None:
                last_cell = cell
            else:
                cellids[cell] = 1
                if last_cell != cell:
                    cellchs[last_cell+"-"+cell] = 1
                last_cell = cell
        return cellids.keys(), cellchs.keys()  


    def save(self):

        f = open(flags.DATA_TAB_PLACE_FILE, 'w')
        json.dump(self.TAB_place,f)
        f.close()
        

    def load(self):

        if os.path.exists(flags.DATA_TAB_PLACE_FILE):
            f = open(flags.DATA_TAB_PLACE_FILE, 'r')
            self.TAB_place = json.load(f)
            f.close()
        else:
            self.TAB_place = {}

if __name__ == "__main__":
    t = Trip()
    for i in range(130):
        t.detect()




